package com.kjtpay.design_pattern.simple_factory;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.kjtpay.design_pattern.R;

public class SimpleFactoryActivity extends AppCompatActivity {

    public static void launch(Context context) {
        if (null != context) {
            Intent intent = new Intent();
            intent.setClass(context, SimpleFactoryActivity.class);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        }
    }

    private EditText numberAEditText;
    private EditText numberBEditText;
    private TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_factory);
        setTitle("简单工厂模式");

        numberAEditText = (EditText)findViewById(R.id.numberAEditText);
        numberBEditText = (EditText)findViewById(R.id.numberBEditText);
        resultTextView = (TextView)findViewById(R.id.resultTextView);
    }

    public void onAddButtonClick(View view) {
        doOperate("+");
    }

    public void onSubButtonClick(View view) {
        doOperate("-");
    }

    public void onMultiplyButtonClick(View view) {
        doOperate("*");
    }

    public void onDivideButtonClick(View view) {
        doOperate("/");
    }

    private void doOperate(String operate) {
        try {
            double numberA = Double.parseDouble(this.numberAEditText.getText().toString());
            double numberB = Double.parseDouble(this.numberBEditText.getText().toString());
            Operation operation = OperationFactory.createOperation(operate);
            operation.setNumberA(numberA);
            operation.setNumberB(numberB);
            double result = operation.GetResult();
            this.resultTextView.setText(String.valueOf(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}